@extends('layouts.app')

@section('title', '我的')

@section('main-content')
<div class="user-header">
    <div class="settings-icon" id="settings-btn">
        ⚙️
    </div>
    <div class="user-avatar" id="user-avatar-display">
        @if(Auth::user()->avatar)
            <img src="{{ Storage::url(Auth::user()->avatar) }}" alt="头像" class="avatar-img">
        @else
            👤
        @endif
    </div>
    <div class="user-name">
        {{ Auth::user()->nickname ?: Auth::user()->name }}
{{--        @if(Auth::user()->isMember())--}}
{{--            <span class="membership-badge">--}}
{{--                @if(Auth::user()->membership_type === 'permanent')--}}
{{--                    👑--}}
{{--                @else--}}
{{--                    💎--}}
{{--                @endif--}}
{{--            </span>--}}
{{--        @endif--}}
    </div>
    <div class="user-id">
{{--        ID: {{ Auth::user()->id }}--}}
        @if(Auth::user()->isMember())
            <span class="membership-status">{{ Auth::user()->getMembershipTypeName() }}会员</span>
        @endif
    </div>
</div>

<div class="menu-list">
    <div class="menu-item" onclick="window.location.href='{{ route('membership.benefits') }}'">
        <div class="menu-item-left">
            <div class="menu-icon" style="color: #ffd700;">👑</div>
            <div class="menu-text">
                @if(Auth::user()->isMember())
                    会员中心
                    <span class="membership-indicator">{{ Auth::user()->getMembershipTypeName() }}</span>
                @else
                    <span style="color: #f59e0b">立即升级VIP</span>
                @endif
            </div>
        </div>
        <div class="menu-arrow">›</div>
    </div>

    <div class="menu-item" onclick="window.location.href='{{ route('user.books') }}'">
        <div class="menu-item-left">
            <div class="menu-icon">📚</div>
            <div class="menu-text">账本管理</div>
        </div>
        <div class="menu-arrow">›</div>
    </div>

    @if (Auth::user()->default_book_id)
        <div class="menu-item" onclick="window.location.href='{{ route('user.books.categories', ['book' => Auth::user()->default_book_id]) }}'">
            <div class="menu-item-left">
                <div class="menu-icon">📂</div>
                <div class="menu-text">分类管理</div>
            </div>
            <div class="menu-arrow">›</div>
        </div>

        <div class="menu-item" onclick="window.location.href='{{ route('auto-transaction.index') }}?book_id={{ Auth::user()->default_book_id }}'">
            <div class="menu-item-left">
                <div class="menu-icon">🔄</div>
                <div class="menu-text">定时记账</div>
            </div>
            <div class="menu-arrow">›</div>
        </div>
    @endif

    <div class="menu-item" onclick="window.location.href='{{ route('bill-export.index') }}'">
        <div class="menu-item-left">
            <div class="menu-icon">📊</div>
            <div class="menu-text">账单导出</div>
        </div>
{{--        <div class="menu-badge">会员</div>--}}
        <div class="menu-arrow">›</div>
    </div>

    @if(!Auth::user()->openid)
    <div class="menu-item" id="bind-wechat-btn">
        <div class="menu-item-left">
            <div class="menu-icon" style="color: #07C160;">WeChat</div>
            <div class="menu-text">绑定微信</div>
        </div>
        <div class="menu-arrow">›</div>
    </div>
    @endif

    <div class="menu-item" onclick="window.location.href='{{ route('about.us') }}'">
        <div class="menu-item-left">
            <div class="menu-icon" style="color: #667eea;">ℹ️</div>
            <div class="menu-text">关于我们</div>
        </div>
        <div class="menu-arrow">›</div>
    </div>
</div>

<!-- 设置页面 -->
<div class="settings-page" id="settings-page">
    <div class="page-header">
        <div class="back-btn" id="back-from-settings" title="返回">
            <span>‹</span>
        </div>
        <div class="page-title">设置</div>
    </div>

    <div class="settings-menu-list">
        <div class="menu-item" id="personal-info-btn">
            <div class="menu-item-left">
                <div class="menu-icon">👤</div>
                <div class="menu-text">个人信息</div>
            </div>
            <div class="menu-arrow">›</div>
        </div>

        <div class="menu-item" id="change-password-btn">
            <div class="menu-item-left">
                <div class="menu-icon">🔒</div>
                <div class="menu-text">修改密码</div>
            </div>
            <div class="menu-arrow">›</div>
        </div>

        @if(Auth::user()->openid)
        <div class="menu-item" id="unbind-wechat-btn">
            <div class="menu-item-left">
                <div class="menu-icon" style="color: #07C160;">WeChat</div>
                <div class="menu-text">解绑微信</div>
            </div>
            <div class="menu-arrow">›</div>
        </div>
        @endif

        <div class="menu-item" id="logout-btn">
            <div class="menu-item-left">
                <div class="menu-icon" style="color: #e53e3e;">🚪</div>
                <div class="menu-text" style="color: #e53e3e;">退出登录</div>
            </div>
            <div class="menu-arrow">›</div>
        </div>
    </div>
</div>

<!-- 个人信息弹窗 -->
<div class="record-form" id="personal-info-modal">
    <div class="record-form-content">
        <div class="record-form-header">
            <div class="record-form-title">个人信息</div>
            <div class="close-btn" id="close-personal-info">✕</div>
        </div>

        <form id="personal-info-form" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
                <label class="form-label">头像</label>
                <div class="avatar-upload-container">
                    <div class="avatar-preview" id="avatar-preview">
                        @if(Auth::user()->avatar)
                            <img src="{{ Storage::url(Auth::user()->avatar) }}" alt="头像" class="avatar-preview-img">
                        @else
                            <div class="avatar-placeholder">👤</div>
                        @endif
                    </div>
                    <div class="avatar-upload-actions">
                        <input type="file" id="avatar-input" name="avatar" accept="image/*" style="display: none;">
                        <button type="button" class="btn-upload" onclick="document.getElementById('avatar-input').click()">选择头像</button>
                        @if(Auth::user()->avatar)
                            <button type="button" class="btn-remove" id="remove-avatar-btn">删除头像</button>
                        @endif
                    </div>
                </div>
                <div class="error-message" id="avatar-error"></div>
                <div class="form-hint">支持JPG、PNG、GIF格式，文件大小不超过2MB</div>
            </div>

            <div class="form-group">
                <label class="form-label">昵称</label>
                <input type="text" class="form-input" id="nickname" name="nickname" value="{{ Auth::user()->nickname ?? '' }}" maxlength="10" placeholder="请输入昵称（最多10个字符）">
                <div class="error-message" id="nickname-error"></div>
                <div class="form-hint">昵称用于显示，可随时修改</div>
            </div>

            <button type="submit" class="btn btn-primary">保存</button>
        </form>
    </div>
</div>

<!-- 修改密码弹窗 -->
<div class="record-form" id="change-password-modal">
    <div class="record-form-content">
        <div class="record-form-header">
            <div class="record-form-title">修改密码</div>
            <div class="close-btn" id="close-change-password">✕</div>
        </div>

        <form id="change-password-form">
            @csrf
            <div class="form-group">
                <label class="form-label">当前密码</label>
                <input type="password" class="form-input" id="current-password" name="current_password" required>
                <div class="error-message" id="current-password-error"></div>
            </div>

            <div class="form-group">
                <label class="form-label">新密码</label>
                <input type="password" class="form-input" id="new-password" name="password" required>
                <div class="error-message" id="password-error"></div>
            </div>

            <div class="form-group">
                <label class="form-label">确认新密码</label>
                <input type="password" class="form-input" id="confirm-new-password" name="password_confirmation" required>
                <div class="error-message" id="password-confirmation-error"></div>
            </div>

            <button type="submit" class="btn btn-primary">确认修改</button>
        </form>
    </div>
</div>

<!-- 微信绑定二维码弹窗 -->
<div class="record-form" id="wechat-bind-modal">
    <div class="record-form-content">
        <div class="record-form-header" style="margin-bottom: 0">
            <div class="record-form-title">绑定微信</div>
            <div class="close-btn" id="close-wechat-bind">✕</div>
        </div>

        <div class="wechat-bind-content">
            <div class="qr-code-container">
                <!-- <div class="qr-code-placeholder">
                    <div class="qr-code-icon">📱</div>
                    <div class="qr-code-text">微信扫码关注公众号</div>
                </div> -->
                <!-- 这里可以放置实际的二维码图片 -->
                <img src="{{ asset('image/wechat-qr.jpg') }}" alt="微信公众号二维码" class="qr-code-img">
            </div>

            <div class="bind-steps">
                <div class="step-item">
                    <div class="step-number">1</div>
                    <div class="step-text">使用微信扫描上方二维码</div>
                </div>
                <div class="step-item">
                    <div class="step-number">2</div>
                    <div class="step-text">关注公众号，菜单栏进入</div>
                </div>
                <div class="step-item">
                    <div class="step-number">3</div>
                    <div class="step-text">登录并打开本页面完成绑定</div>
                </div>
            </div>

            <div class="bind-tips">
                <div class="tips-title">💡 温馨提示</div>
                <div class="tips-content">
                    绑定微信后，您可以通过微信公众号快速记账，享受更便捷的记账体验！
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 退出登录确认弹窗 -->
<div class="modal fade" id="logoutModal" tabindex="-1" aria-labelledby="logoutModalLabel" >
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="logoutModalLabel">退出登录</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                确定要退出登录吗？
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmLogout">确定退出</button>
            </div>
        </div>
    </div>
</div>

<!-- 头像裁剪模态框 -->
<div class="avatar-crop-modal" id="avatar-crop-modal">
    <div class="avatar-crop-container">
        <div class="avatar-crop-header">
            <div class="avatar-crop-title">裁剪头像</div>
            <div class="close-btn" id="close-avatar-crop">✕</div>
        </div>
        <div class="avatar-crop-body">
            <div class="avatar-crop-img-container">
                <img id="crop-image" src="" alt="待裁剪的图片">
            </div>
            <div class="avatar-crop-preview" id="avatar-crop-preview"></div>
        </div>
        <div class="avatar-crop-actions">
            <button type="button" class="btn-crop btn-crop-cancel" id="cancel-crop">取消</button>
            <button type="button" class="btn-crop btn-crop-apply" id="apply-crop">应用</button>
        </div>
    </div>
</div>
@endsection

@push('styles')
<link rel="stylesheet" href="{{ asset('/css/cropper.min.css') }}">
<style>
.app-container {
    padding: 0 !important;
    padding-bottom: 80px !important;
}
/* 用户头部样式 */
.user-header {
    text-align: center;
    padding: 30px 0;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border-radius: 0 0 30px 30px;
    margin: -20px -20px 30px -20px;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
    position: relative;
}

/* 设置图标样式 */
.settings-icon {
    position: absolute;
    top: 25%;
    right: 10%;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid rgba(255, 255, 255, 0.3);
}

.settings-icon:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
    box-shadow: 0 4px 15px rgba(255, 255, 255, 0.2);
}

/* 设置页面样式 */
.settings-page {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #f8fafc;
    z-index: 1001;
    transform: translateX(100%);
    transition: transform 0.3s ease;
    overflow-y: auto;
}

.settings-page.active {
    transform: translateX(0);
}

.settings-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    position: relative;
    z-index: 1001;
}

.back-btn {
    z-index: 1005;
}

.settings-menu-list {
    padding: 20px;
}

.user-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36px;
    margin: 0 auto 15px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    transition: all 0.3s ease;
    cursor: pointer;
    margin-top: 15px;
    overflow: hidden;
}

.user-avatar:hover {
    transform: scale(1.05);
    box-shadow: 0 5px 20px rgba(255, 255, 255, 0.3);
}

.avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
}

.user-name {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 5px;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-id {
    font-size: 14px;
    opacity: 0.8;
}

/* 菜单列表样式 */
.menu-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px;
    border-bottom: 1px solid #f1f5f9;
    cursor: pointer;
    transition: all 0.3s ease;
    background: white;
    position: relative;
    overflow: hidden;
}

.menu-item:last-child {
    border-bottom: none;
}

.menu-item:hover {
    background: linear-gradient(90deg, #f8fafc 0%, #e6f3ff 100%);
    transform: translateX(5px);
}

.menu-item:active {
    transform: translateX(3px) scale(0.98);
}

.menu-item.clicked {
    background: linear-gradient(90deg, #e6f3ff 0%, #dbeafe 100%);
    transform: scale(0.98);
}

.menu-item-left {
    display: flex;
    align-items: center;
}

.menu-icon {
    width: 40px;
    height: 40px;
    border-radius: 12px;
    background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    margin-right: 15px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.menu-item:hover .menu-icon {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.menu-text {
    font-size: 16px;
    font-weight: 500;
    color: #2d3748;
    transition: all 0.3s ease;
}

.menu-item:hover .menu-text {
    color: #667eea;
    font-weight: 600;
}

.menu-arrow {
    font-size: 18px;
    color: #a0aec0;
    transition: all 0.3s ease;
    font-weight: bold;
}

.menu-item:hover .menu-arrow {
    color: #667eea;
    transform: translateX(5px) scale(1.2);
}

/* 会员徽章样式 */
.menu-badge {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    font-size: 11px;
    font-weight: 600;
    padding: 3px 8px;
    border-radius: 12px;
    margin-right: 10px;
    box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
}

.menu-badge.premium {
    background: linear-gradient(135deg, #f59e0b, #d97706);
    box-shadow: 0 2px 6px rgba(245, 158, 11, 0.3);
    animation: premiumGlow 2s ease-in-out infinite alternate;
}

@keyframes premiumGlow {
    0% {
        box-shadow: 0 2px 6px rgba(245, 158, 11, 0.3);
    }
    100% {
        box-shadow: 0 2px 10px rgba(245, 158, 11, 0.5), 0 0 15px rgba(245, 158, 11, 0.2);
    }
}

/* 会员专享菜单项样式 */
.menu-item.member-only {
    position: relative;
    background: linear-gradient(90deg, #fef3c7, #fde68a);
    border: 1px solid #f59e0b;
}

.menu-item.member-only:hover {
    background: linear-gradient(90deg, #fde68a, #fcd34d);
    transform: translateX(5px);
}

.menu-item.member-only .menu-icon {
    background: linear-gradient(135deg, #f59e0b, #d97706);
    color: white;
    box-shadow: 0 2px 8px rgba(245, 158, 11, 0.3);
}

.menu-item.member-only .menu-text {
    color: #92400e;
    font-weight: 600;
}

.menu-item.member-only .menu-arrow {
    color: #d97706;
}

/* 弹窗样式 */
.record-form {
    position: fixed;
    top: 50%;
    left: 50%;
    z-index: 2000;
}

.record-form.active {
    opacity: 1;
    visibility: visible;
    transform: translate(-50%, -50%) scale(1);
}

.record-form-content {
    padding: 30px;
}

.record-form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e2e8f0;
}

.record-form-title {
    font-size: 20px;
    font-weight: 600;
    color: #2d3748;
}

.close-btn {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #f7fafc;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #a0aec0;
    transition: all 0.3s ease;
}

.close-btn:hover {
    background: #fed7d7;
    color: #e53e3e;
    transform: scale(1.1);
}

.form-group {
    margin-bottom: 20px;
    position: relative;
}

.form-group.focused .form-label {
    color: #667eea;
    transform: translateY(-2px);
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #4a5568;
    font-size: 14px;
    transition: all 0.3s ease;
}

.form-input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    font-size: 16px;
    transition: all 0.3s ease;
    background: #f8fafc;
}

.form-input:not([readonly]):hover {
    border-color: #cbd5e0;
    background: #f7fafc;
}

.form-input:focus {
    outline: none;
    border-color: #667eea;
    background: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15), 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input.error {
    border-color: #e53e3e;
    background: #fed7d7;
    animation: errorShake 0.6s ease-out;
}

.form-input[readonly] {
    background: #f1f5f9;
    color: #718096;
    cursor: not-allowed;
}

.error-message {
    color: #e53e3e;
    font-size: 12px;
    margin-top: 5px;
    display: none;
    animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-5px); }
    to { opacity: 1; transform: translateY(0); }
}

.btn {
    width: 100%;
    padding: 14px;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a67d8, #6b46c1);
}

.btn-primary:active {
    transform: translateY(0);
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-primary:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    background: #a0aec0;
}

/* 加载动画 */
.btn-loading {
    position: relative;
    color: transparent;
}

.btn-loading::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 20px;
    border: 2px solid transparent;
    border-top: 2px solid white;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: translate(-50%, -50%) rotate(0deg); }
    100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* 成功提示动画 */
.success-animation {
    animation: successPulse 0.6s ease-out;
}

@keyframes successPulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

/* 错误提示动画 */
.error-animation {
    animation: errorShake 0.6s ease-out;
}

@keyframes errorShake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    75% { transform: translateX(5px); }
}

/* 页面加载动画 */
.menu-item {
    animation: slideInUp 0.5s ease-out;
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 头像上传样式 */
.avatar-upload-container {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 10px;
}

.avatar-preview {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    border: 2px solid #e2e8f0;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    background: #f8fafc;
}

.avatar-preview-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-placeholder {
    font-size: 32px;
    color: #a0aec0;
}

.avatar-upload-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.btn-upload, .btn-remove {
    padding: 8px 16px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-upload {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-upload:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-remove {
    background: #fed7d7;
    color: #e53e3e;
    border: 1px solid #feb2b2;
}

.btn-remove:hover {
    background: #fbb6ce;
    transform: translateY(-1px);
}

.form-hint {
    font-size: 12px;
    color: #718096;
    margin-top: 5px;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .record-form {
        width: 95%;
        max-width: none;
    }

    .record-form-content {
        padding: 20px;
    }

    .menu-list {
        margin: 15px;
    }

    .user-header {
        padding: 25px 0;
    }

    .user-avatar {
        width: 70px;
        height: 70px;
        font-size: 32px;
        margin-top: 15px;
    }

    .user-name {
        font-size: 20px;
    }

    .avatar-upload-container {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }

    .avatar-upload-actions {
        flex-direction: row;
        gap: 10px;
    }

    .btn-upload, .btn-remove {
        padding: 6px 12px;
        font-size: 12px;
    }
}

/* 头像裁剪相关样式 */
.cropper-container {
    width: 100%;
    max-width: 500px;
    margin: 0 auto;
}

.avatar-crop-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 2100;
    display: none;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
}

.avatar-crop-container {
    background: white;
    border-radius: 15px;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.avatar-crop-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #e2e8f0;
}

.avatar-crop-title {
    font-size: 18px;
    font-weight: 600;
    color: #2d3748;
}

.avatar-crop-body {
    padding: 20px;
    overflow: hidden;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.avatar-crop-img-container {
    width: 100%;
    max-height: 50vh;
    overflow: hidden;
    margin-bottom: 20px;
}

.avatar-crop-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    border: 2px solid #e2e8f0;
    margin: 0 auto 20px;
}

.avatar-crop-actions {
    display: flex;
    justify-content: space-between;
    width: 100%;
    padding: 15px 20px;
    border-top: 1px solid #e2e8f0;
}

.btn-crop-cancel {
    background: #e2e8f0;
    color: #4a5568;
}

.btn-crop-cancel:hover {
    background: #cbd5e0;
}

.btn-crop-apply {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
}

.btn-crop-apply:hover {
    background: linear-gradient(135deg, #5a67d8, #6b46c1);
}

/* 微信绑定弹窗样式 */
.wechat-bind-content {
    padding: 30px 20px;
    text-align: center;
}

.qr-code-container {
    margin-bottom: 30px;
}

.qr-code-placeholder {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    border: 2px dashed #cbd5e0;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #f7fafc;
    transition: all 0.3s ease;
}

.qr-code-placeholder:hover {
    border-color: #a0aec0;
    background: #edf2f7;
}

.qr-code-icon {
    font-size: 48px;
    margin-bottom: 10px;
    opacity: 0.6;
}

.qr-code-text {
    color: #718096;
    font-size: 14px;
    font-weight: 500;
}

.qr-code-img {
    width: 200px;
    height: 200px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.bind-steps {
    margin-bottom: 30px;
    text-align: left;
}

.step-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    padding: 12px 16px;
    background: #f7fafc;
    border-radius: 8px;
    border-left: 4px solid #667eea;
}

.step-number {
    width: 24px;
    height: 24px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 600;
    margin-right: 12px;
    flex-shrink: 0;
}

.step-text {
    color: #4a5568;
    font-size: 14px;
    line-height: 1.5;
}

.bind-tips {
    background: linear-gradient(135deg, #e6fffa, #f0fff4);
    border: 1px solid #9ae6b4;
    border-radius: 8px;
    padding: 16px;
    text-align: left;
}

.tips-title {
    color: #2f855a;
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 8px;
}

.tips-content {
    color: #38a169;
    font-size: 13px;
    line-height: 1.5;
}

.btn-crop {
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-crop:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
@endpush

@push('scripts')
<script src="{{ asset('/js/cropper.min.js') }}"></script>
<script>
$(document).ready(function() {
    // 设置页面交互
    $('#settings-btn').on('click', function() {
        console.log('Settings button clicked');
        $('#settings-page').addClass('active');
    });

    $('#back-from-settings').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('Back button clicked');
        $('#settings-page').removeClass('active');
    });

    // 添加触摸事件支持
    $('#back-from-settings').on('touchstart', function(e) {
        e.preventDefault();
        e.stopPropagation();
        console.log('Back button touched');
        $('#settings-page').removeClass('active');
    });

    // 添加ESC键支持
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape' && $('#settings-page').hasClass('active')) {
            $('#settings-page').removeClass('active');
        }
    });

    // 添加双击返回支持（备用方案）
    $('.settings-header').on('dblclick', function(e) {
        if (e.target === this || $(e.target).hasClass('settings-title')) {
            $('#settings-page').removeClass('active');
        }
    });

    // 个人信息弹窗
    $('#personal-info-btn').on('click', function() {
        $('#personal-info-modal').addClass('active');
        $('#overlay').addClass('active');
    });

    $('#close-personal-info').on('click', function() {
        $('#personal-info-modal').removeClass('active');
        $('#overlay').removeClass('active');
    });

    // 修改密码弹窗
    $('#change-password-btn').on('click', function() {
        $('#change-password-modal').addClass('active');
        $('#overlay').addClass('active');
    });

    $('#close-change-password').on('click', function() {
        $('#change-password-modal').removeClass('active');
        $('#overlay').removeClass('active');
    });

    // 微信绑定（主页面）
    $('#bind-wechat-btn').on('click', function() {
        @if(strpos(request()->header('User-Agent'), 'MicroMessenger') !== false)
            // 在微信浏览器中
            window.location.href = '{{ route("wechat.bind") }}';
        @else
            // 显示微信绑定二维码弹窗
            $('#wechat-bind-modal').addClass('active');
            $('#overlay').addClass('active');
        @endif
    });

    // 关闭微信绑定弹窗
    $('#close-wechat-bind').on('click', function() {
        $('#wechat-bind-modal').removeClass('active');
        $('#overlay').removeClass('active');
    });

    // 点击overlay关闭微信绑定弹窗
    $('#overlay').on('click', function() {
        if ($('#wechat-bind-modal').hasClass('active')) {
            $('#wechat-bind-modal').removeClass('active');
            $('#overlay').removeClass('active');
        }
    });

    // 微信解绑（设置页面）
    $('#unbind-wechat-btn').on('click', function() {
        if(confirm('确定要解绑微信吗？')) {
            $.ajax({
                url: '{{ route("wechat.unbind") }}',
                method: 'POST',
                data: {
                    _token: $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    showToast('微信解绑成功！');
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                },
                error: function() {
                    showError('解绑失败，请重试');
                }
            });
        }
    });

    // 退出登录
    $('#logout-btn').on('click', function() {
        $('#logoutModal').modal('show');
    });

    // 确认退出登录
    $('#confirmLogout').on('click', function() {
        $.ajax({
            url: '{{ route("logout") }}',
            method: 'POST',
            data: {
                _token: $('meta[name="csrf-token"]').attr('content')
            },
            success: function() {
                window.location.href = '{{ route("login") }}';
            },
            error: function() {
                $('#logoutModal').modal('hide');
                showError('退出登录失败，请重试');
            }
        });
    });

    let cropper;
    let croppedCanvas;
    let originalFile;

    // 头像预览功能
    $('#avatar-input').on('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 验证文件类型
            const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'];
            if (!allowedTypes.includes(file.type)) {
                $('#avatar-error').text('请选择JPG、PNG、GIF格式的图片').show();
                return;
            }

            // 验证文件大小（2MB）
            if (file.size > 2 * 1024 * 1024) {
                $('#avatar-error').text('图片大小不能超过2MB').show();
                return;
            }

            $('#avatar-error').hide();
            originalFile = file;

            // 打开裁剪模态框
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#crop-image').attr('src', e.target.result);
                $('#avatar-crop-modal').css('display', 'flex');

                // 初始化裁剪器
                if (cropper) {
                    cropper.destroy();
                }

                const image = document.getElementById('crop-image');
                cropper = new Cropper(image, {
                    aspectRatio: 1, // 1:1 正方形
                    viewMode: 1,
                    dragMode: 'move',
                    autoCropArea: 0.8,
                    restore: false,
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                    toggleDragModeOnDblclick: false,
                    preview: '#avatar-crop-preview'
                });
            };
            reader.readAsDataURL(file);
        }
    });

    // 关闭裁剪模态框
    $('#close-avatar-crop, #cancel-crop').on('click', function() {
        $('#avatar-crop-modal').hide();
        $('#avatar-input').val('');
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
    });

    // 应用裁剪
    $('#apply-crop').on('click', function() {
        if (!cropper) return;

        // 获取裁剪后的Canvas
        croppedCanvas = cropper.getCroppedCanvas({
            width: 300,
            height: 300,
            minWidth: 100,
            minHeight: 100,
            maxWidth: 1000,
            maxHeight: 1000,
            fillColor: '#fff',
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high',
        });

        // 显示裁剪后的预览
        const croppedImageUrl = croppedCanvas.toDataURL(originalFile.type);
        $('#avatar-preview').html(`<img src="${croppedImageUrl}" alt="头像预览" class="avatar-preview-img">`);

        // 显示删除按钮
        if ($('#remove-avatar-btn').length === 0) {
            $('.avatar-upload-actions').append('<button type="button" class="btn-remove" id="remove-avatar-btn">删除头像</button>');
        }

        // 关闭裁剪模态框
        $('#avatar-crop-modal').hide();
        cropper.destroy();
        cropper = null;
    });

    // 删除头像功能
    $(document).on('click', '#remove-avatar-btn', function() {
        $('#avatar-input').val('');
        $('#avatar-preview').html('<div class="avatar-placeholder">👤</div>');
        $(this).remove();
        $('#avatar-error').hide();
        croppedCanvas = null;
    });

    // 个人信息表单提交
    $('#personal-info-form').on('submit', function(e) {
        e.preventDefault();

        // 清除之前的错误信息
        $('.error-message').hide();
        $('.form-input').removeClass('error');

        const formData = new FormData(this);
        const submitBtn = $(this).find('button[type="submit"]');

        // 如果有裁剪后的图片，将其添加到FormData
        if (croppedCanvas) {
            croppedCanvas.toBlob(function(blob) {
                formData.set('avatar', blob, originalFile.name);
                submitAjax(formData, submitBtn);
            }, originalFile.type);
        } else {
            submitAjax(formData, submitBtn);
        }
    });

    function submitAjax(formData, submitBtn) {
        $.ajax({
            url: '{{ route("user.profile.update") }}',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            beforeSend: function() {
                submitBtn.prop('disabled', true).addClass('btn-loading').text('保存中...');
            },
            success: function(response) {
                if (response.success) {
                    submitBtn.removeClass('btn-loading').addClass('success-animation');
                    showSuccess('个人信息已更新');

                    setTimeout(() => {
                        $('#personal-info-modal').removeClass('active');
                        $('#overlay').removeClass('active');

                        // 更新页面显示的用户名和头像
                        const displayName = response.user.nickname || response.user.name;
                        $('.user-name').contents().filter(function() {
                            return this.nodeType === 3; // 文本节点
                        }).first().replaceWith(displayName);
                        if (response.user.avatar) {
                            $('#user-avatar-display').html(`<img src="${response.user.avatar}" alt="头像" class="avatar-img">`);
                        }
                        submitBtn.removeClass('success-animation');

                        // 重置裁剪相关变量
                        croppedCanvas = null;
                        originalFile = null;
                    }, 800);
                } else {
                    submitBtn.removeClass('btn-loading').addClass('error-animation');
                    showError(response.message || '更新失败，请重试');
                    setTimeout(() => submitBtn.removeClass('error-animation'), 600);
                }
                submitBtn.prop('disabled', false).text('保存');
            },
            error: function(xhr) {
                submitBtn.prop('disabled', false).removeClass('btn-loading').addClass('error-animation').text('保存');
                setTimeout(() => submitBtn.removeClass('error-animation'), 600);

                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    for (let field in errors) {
                        if (field === 'avatar') {
                            $('#avatar-error').text(errors[field][0]).show();
                        } else {
                            $(`#${field}`).addClass('error');
                            $(`#${field}-error`).text(errors[field][0]).show();
                        }
                    }
                } else {
                    showError('更新失败，请重试');
                }
            }
        });
    }

    // 修改密码表单提交
    $('#change-password-form').on('submit', function(e) {
        e.preventDefault();

        // 清除之前的错误信息
        $('.error-message').hide();
        $('.form-input').removeClass('error');

        // 验证表单
        if (!validatePasswordForm()) {
            return;
        }

        const formData = $(this).serialize();
        const submitBtn = $(this).find('button[type="submit"]');

        $.ajax({
            url: '{{ route("user.change-password") }}',
            method: 'POST',
            data: formData,
            beforeSend: function() {
                submitBtn.prop('disabled', true).addClass('btn-loading').text('修改中...');
            },
            success: function(response) {
                if (response.success) {
                    submitBtn.removeClass('btn-loading').addClass('success-animation');
                    showSuccess('密码修改成功');

                    setTimeout(() => {
                        $('#change-password-modal').removeClass('active');
                        $('#overlay').removeClass('active');
                        $('#change-password-form')[0].reset();
                        submitBtn.removeClass('success-animation');
                    }, 800);
                } else {
                    submitBtn.removeClass('btn-loading').addClass('error-animation');
                    showError(response.message || '修改失败，请重试');
                    setTimeout(() => submitBtn.removeClass('error-animation'), 600);
                }
                submitBtn.prop('disabled', false).text('确认修改');
            },
            error: function(xhr) {
                submitBtn.prop('disabled', false).removeClass('btn-loading').addClass('error-animation').text('确认修改');
                setTimeout(() => submitBtn.removeClass('error-animation'), 600);

                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    for (let field in errors) {
                        $(`#${field.replace('_', '-')}`).addClass('error');
                        $(`#${field.replace('_', '-')}-error`).text(errors[field][0]).show();
                    }
                } else {
                    showError('修改失败，请重试');
                }
            }
        });
    });

    // 密码表单验证
    function validatePasswordForm() {
        let isValid = true;

        const currentPassword = $('#current-password').val();
        const newPassword = $('#new-password').val();
        const confirmNewPassword = $('#confirm-new-password').val();

        if (!currentPassword) {
            $('#current-password').addClass('error');
            $('#current-password-error').text('请输入当前密码').show();
            isValid = false;
        }

        if (!newPassword || newPassword.length < 6) {
            $('#new-password').addClass('error');
            $('#password-error').text('新密码至少6位').show();
            isValid = false;
        }

        if (newPassword !== confirmNewPassword) {
            $('#confirm-new-password').addClass('error');
            $('#password-confirmation-error').text('两次输入的新密码不一致').show();
            isValid = false;
        }

        return isValid;
    }

    // 实时验证确认密码
    $('#confirm-new-password').on('input', function() {
        const newPassword = $('#new-password').val();
        const confirmNewPassword = $(this).val();

        if (confirmNewPassword && newPassword !== confirmNewPassword) {
            $(this).addClass('error');
            $('#password-confirmation-error').text('两次输入的新密码不一致').show();
        } else {
            $(this).removeClass('error');
            $('#password-confirmation-error').hide();
        }
    });

    // 输入框焦点效果
    $('.form-input').on('focus', function() {
        $(this).parent().addClass('focused');
    }).on('blur', function() {
        $(this).parent().removeClass('focused');
    });

    // 清除错误状态
    $('.form-input').on('input', function() {
        $(this).removeClass('error');
        $(this).siblings('.error-message').hide();
    });

    // 菜单项点击效果
    $('.menu-item').on('click', function() {
        $(this).addClass('clicked');
        setTimeout(() => {
            $(this).removeClass('clicked');
        }, 200);
    });

    // 用户头像点击效果
    $('.user-avatar').on('click', function() {
        $(this).addClass('success-animation');
        setTimeout(() => {
            $(this).removeClass('success-animation');
        }, 600);
    });

    // 页面加载动画
    $('.menu-item').each(function(index) {
        $(this).css({
            'animation-delay': (index * 0.1) + 's'
        });
    });

    // 点击遮罩层关闭弹窗
    $('#overlay').on('click', function() {
        $('.record-form.active').removeClass('active');
        $(this).removeClass('active');
    });
});
</script>
@endpush
